package cn.com.xinjinfu.pdoulcProduct.engine;

import java.io.EOFException;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.util.Log;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.android.volley.toolbox.Volley;
import com.shove.gateway.GeneralRestGateway;

import cn.com.xinjinfu.pdoulcProduct.manager.ConstantManager;
import cn.com.xinjinfu.pdoulcProduct.manager.L;
import cn.com.xinjinfu.pdoulcProduct.manager.ToastManager;
import cn.com.xinjinfu.pdoulcProduct.manager.UIManager;
import cn.com.xinjinfu.pdoulcProduct.view.LoadStatusBox;

/**
 * 所有网络访问的入口
 */
public class DataHandler {
    private static final String TAG = "DataHandler";
    public static String DOMAIN;
    public static String WEBURL;
    public static String URL_DOMAIN;
    public static String KEY = "DFGgrgkl45DGkj8g";
    public static String KEY_DATA = "GDgLwwdK270Qj1w4";
    private static Map<String, String> parameters;

    static {
        int x = 0;
        switch (x) {
            case 0:      //测试本地
                DOMAIN = "http://dev.pdoulicai.com";
//                DOMAIN = "http://172.32.1.197:9005";//红岩
                WEBURL = "http://app.pdoulicai.com";
                break;
            case 1:      //正式外网
                DOMAIN = "http://srv.pdoulicai.com";
                WEBURL = "https://m.pdoulicai.com";
                break;
        }
        URL_DOMAIN = DOMAIN + "/app/services";

    }

    public static String encrypt3DES(String input) {
        return com.shove.security.Encrypt.encrypt3DES(input, KEY_DATA);
    }

    /**
     * 获取加密的url 不会破坏输入的参数
     *
     * @param map 参数
     * @return
     */

    public static String getBuildUrl(Map<String, String> map) {
        try {
            Map<String, String> maps = new HashMap<String, String>();
            maps.putAll(map);
            String data = GeneralRestGateway.buildUrl(URL_DOMAIN, KEY, maps);
            Log.i(TAG, data);
            return data;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取加密的url  会破坏输入的参数
     *
     * @param map 参数
     * @return
     */
    public static String getBuildUrl2(Map<String, String> map) {
        try {
            String url = GeneralRestGateway.buildUrl(URL_DOMAIN, KEY, map);
            Log.v(TAG, url);
            return url;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 网络请求ver2.0
     *
     * @param showProgress true->显示进度框
     * @param errorHandler 是否处理错误回调
     *                     true->错误回调中会使用handler
     */
    public static void sendRequest(RequestQueue requen, Map<String, String> param,
                                   Context ct, Handler handler, boolean showProgress, boolean errorHandler, boolean showLog) {
        Dialog dg = null;
        if (!DataHandler.isNetworkConnected(ct))
            showProgress = false;
        if (showProgress) {
            dg = UIManager.getLoadingDialog(ct, errorHandler ? "加载中..." : "处理中...");
            dg.setCancelable(true);
            dg.setCanceledOnTouchOutside(false);
            dg.show();
        }
        JsonListener mListener = new JsonListener(ct, handler, dg, errorHandler);
        JsonErrorListener mError = new JsonErrorListener(ct, errorHandler ? handler : null, dg, showLog);
        JsonRequest<JSONObject> jor = new JsonObjectRequest(DataHandler.getBuildUrl2(param), null, mListener, mError);
        requen.add(jor);
    }

//    /**
//     * 网络请求ver2.0
//     * when handler ignore error callback 不管错误回调
//     */
//    public static void sendTrueRequest(RequestQueue requen, Map<String, String> param,
//                                       Context ct, Handler handler, boolean showProgress) {
//        sendRequest(requen, param, ct, handler, showProgress, false, true);
//    }
//
//    /**
//     * 网络请求ver2.0
//     * 不打印log,不显示进度条,
//     */
//    public static void sendSilenceRequest(RequestQueue requen, Map<String, String> param,
//                                          Context ct, Handler handler) {
//        sendRequest(requen, param, ct, handler, false, true, false);
//    }
//
//    /**
//     * 网络请求ver2.0
//     * 请求列表数据,不显示进度条
//     * 需判断msg.what
//     */
//    public static void sendListRequest(RequestQueue requen, Map<String, String> param,
//                                       Context ct, Handler handler) {
//        sendRequest(requen, param, ct, handler, false, true, true);
//    }


    public static ErrorListener getEor(final Context context, final LoadStatusBox loadbox) {
        ErrorListener el = new ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                errorHandler(context, error);
                loadbox.failed();
            }
        };
        return el;
    }

    public static void errorHandler(final Context context, VolleyError error) {
        Throwable th = error.getCause();
        String msg = getErrorMsg(error);
        if (th != null) {
            if (th instanceof ConnectException) {
                ToastManager.showShort(context, msg);
            }
            if (th instanceof UnknownHostException) {
                ToastManager.showShort(context, msg);
            }
            if (th instanceof JSONException) {
                ToastManager.showShort(context, msg);
            }
            if (th instanceof SocketException)
                ToastManager.showShort(context, msg);
            if (th instanceof EOFException)
                ToastManager.showShort(context, msg);
        } else {
            ToastManager.showShort(context, msg);
        }
        L.e("DataHander request Error! msg:" + error.getMessage() +
                "\n cause:" + error.getCause() + "\n" + " local msg:" + error.getLocalizedMessage());
    }


    public static String getErrorMsg(VolleyError error) {
        Throwable th = error.getCause();
        if (th != null) {
            if (th instanceof ConnectException) {
                return "网络异常,请检查网络连接！";
            }
            if (th instanceof UnknownHostException) {
                return "网络异常,请检查网络连接！";
            }
            if (th instanceof JSONException) {
                return "获取数据失败，请稍后重试！";
            }
            if (th instanceof SocketException) {
                return "网络连接超时，请稍后重试！";
            }
        }
        return "获取数据失败，请稍后重试！";
    }


    /**
     * 封装部分网络接口参数
     *
     * @param OPT 对应后台接口功能ID数值
     * @return
     */
    public static Map<String, String> getParameters(String OPT) {
        if (parameters == null) {
            parameters = new HashMap<String, String>();
        } else {
            parameters.clear();
        }
        parameters.put("body", "");
        parameters.put("userId", "");
        parameters.put("deviceType", "2");
        parameters.put("channelId", "");
        parameters.put("OPT", OPT);
        return parameters;
    }

    public static Map<String, String> getNewParameters(String OPT) {
        Map<String, String> parameters = new HashMap<String, String>();
        parameters.put("body", "");
        parameters.put("userId", "");
        parameters.put("deviceType", "2");
        parameters.put("channelId", "");
        parameters.put("OPT", OPT);
        return parameters;
    }


    /**
     * 所有请求通过该方法添加到网络队列
     *
     * @param request
     * @param context
     */
    private static RequestQueue mRequestQueue;

    private static void addRequest(Request request, Context context) {
        // 初始化请求，整个应用中使用
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(context);
        }
        mRequestQueue.add(request);
    }

    /**
     * 封装网络提示
     *
     * @param handler
     * @param context
     * @return
     */
    public static boolean isNetworkConnected(Handler handler, Context context) {
        boolean flag = isNetworkConnected(context);
        if (!flag) {
            handler.sendEmptyMessage(ConstantManager.FAIL_NO_NET);
        }
        return flag;
    }

    /**
     * 检测网络是否可用
     *
     * @return
     */
    public static boolean isNetworkConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        return ni != null && ni.isConnectedOrConnecting();
    }

}

